// pages/client/detail/detail.js
var md5 = require('../../../utils/md5.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    enoughBalance: true,
    recharge: true,
    is_ios: false,
    buyIng: true,
    toView: '',
    base_title: {
      id: 0,
      title: '基本信息'
    },
    base_info: [{
      image: '/img/client/age.png',
      value: '获取中...'
    }, {
      image: '/img/client/location.png',
      value: '获取中...'
    }, {
      image: '/img/client/education.png',
      value: '获取中...'
    }, {
      image: '/img/client/marriage.png',
      value: '获取中...'
    }],
    desc_title: {
      id: 3,
      title: '客户描述'
    },
    array: [{
      first_title: '职业信息',
      data: {
        first: [{
            id: 1,
            name: '职业身份',
            val: '获取中...',
            child_hide: false,
            child: [{
                child_name: '公司名称',
                child_val: '获取中...',
                unit: ''
              },
              {
                child_name: '月均收入',
                child_val: '获取中...',
                unit: '元'
              }
            ]
          },
          {
            id: 2,
            name: '社保公积',
            val: '有社保公积',
            child_hide: false,
            child: [{
                child_name: '缴存基数',
                child_val: '获取中...',
                unit: '元'
              },
              {
                child_name: '月总缴存',
                child_val: '获取中...',
                unit: '元'
              }
            ]
          }
        ]
      }
    }, {
      first_title: '资产信息',
      data: {
        first: [{
            id: 3,
            name: '有无房产',
            val: '获取中...',
            child_hide: false,
            child: [{
                child_name: '房屋现值',
                child_val: '获取中...',
                unit: '万'
              },
              {
                child_name: '月供金额',
                child_val: '获取中...',
                unit: '元'
              },
              {
                child_name: '已还期数',
                child_val: '获取中...',
                unit: '期'
              }
            ]
          },
          {
            id: 4,
            name: '有无车产',
            val: '获取中...',
            child_hide: false,
            child: [{
                child_name: '车辆现值',
                child_val: '获取中...',
                unit: '万'
              },
              {
                child_name: '抵押状态',
                child_val: '获取中...',
                unit: ''
              }
            ]
          },
          {
            id: 5,
            name: '信用卡',
            val: '获取中...',
            child_hide: false,
            child: [{
                child_name: '授信额度',
                child_val: '获取中...',
                unit: '万'
              },
              {
                child_name: '已用额度',
                child_val: '获取中...',
                unit: '万'
              }
            ]
          },
          {
            id: 6,
            name: '微粒贷',
            val: '获取中...',
            child_hide: false,
            child: [{
                child_name: '授信额度',
                child_val: '获取中...',
                unit: '万'
              },
              {
                child_name: '已用额度',
                child_val: '获取中...',
                unit: '万'
              }
            ]
          },
          {
            id: 7,
            name: '寿险保单',
            val: '获取中...',
            child: []
          }
        ]
      }
    }]
  },

  showPopup: function() {
    this.setData({
      buyIng: false
    });
  },

  hiddenPopup: function() {
    this.setData({
      buyIng: true
    });
  },

  // 子项折叠
  fold: function(e) {
    var this_ = this;
    var id = e.currentTarget.dataset.id;
    for (var i = 0; i < this_.data.array.length; i++) {
      for (var j = 0; j < this_.data.array[i].data.first.length; j++) {
        if (id == this_.data.array[i].data.first[j].id) {
          this_.data.array[i].data.first[j].child_hide = !this_.data.array[i].data.first[j].child_hide;
          this_.setData({
            array: this_.data.array
          })
        }
      }
    }
  },

  // 购买
  buyMessage: function(e) {
    var buyType = e.currentTarget.dataset.item;
    var price = e.currentTarget.dataset.price;
    var buy_type = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.id;
    this.setData({
      buyType: buyType,
      cash: price,
      fee_id: id
    })
  },

  callNotice: function(e) {
    var this_ = this;
    var hash = e.currentTarget.dataset.hash;
    if (this.data.detail.out_status == 0) {
      wx.showModal({
        title: '温馨提示',
        content: '该客户已被买断',
        showCancel: false,
        confirmText: '我知道了'
      })
    } else {
      wx.showModal({
        title: '无此权限',
        content: '请先进行抢单操作',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            this_.setData({
              toView: hash
            })
          }
        }
      })
    }
  },

  // 拨打电话
  phonecall: function(e) {
    var mobile = e.currentTarget.dataset.phone;
    wx.getSystemInfo({
      success: function(res) {
        if (res.system.indexOf('iOS') !== -1) {
          wx.makePhoneCall({
            phoneNumber: mobile.toString(),
          })
        } else if (res.system.indexOf('Android') !== -1) {
          wx.showModal({
            title: '拨打电话',
            content: '确定要拨打' + mobile + '？',
            success: function(e) {
              if (e.confirm) {
                wx.makePhoneCall({
                  phoneNumber: mobile.toString()
                })
              }
            }
          })
        }
      }
    })
  },

  // 获取详情信息
  get_detail: function(id) {
    var this_ = this;
    var param = {
      client_id: id
    };
    app.util.api("client/client_detail", 'GET', param, function(data) {
      if (data.data.out_status == 2) {
        this_.setData({
          buyType: 1
        })
      } else {
        this_.setData({
          buyType: 0
        })
      }
      this_.data.base_info[0].value = data.data.age;
      this_.data.base_info[1].value = data.data.city_location;
      this_.data.base_info[2].value = data.data.education;
      this_.data.base_info[3].value = data.data.marital_status;

      // 重设职业信息
      this_.data.array[0].data.first[0].val = data.data.occupation;
      this_.data.array[0].data.first[0].child[0].child_val = data.data.company_name;
      this_.data.array[0].data.first[0].child[1].child_val = data.data.monthly_income;
      if (data.data.social_security == 1) {
        this_.data.array[0].data.first[1].val = '有公积金';
        this_.data.array[0].data.first[1].child[0].child_val = data.data.deposit_base;
        this_.data.array[0].data.first[1].child[1].child_val = data.data.deposit_monthly;
      } else if (data.data.social_security == 2) {
        this_.data.array[0].data.first[1].val = '有社保';
        this_.data.array[0].data.first[1].child[0].child_val = data.data.deposit_base;
        this_.data.array[0].data.first[1].child[1].child_val = data.data.deposit_monthly;
      } else {
        this_.data.array[0].data.first[1].val = '无';
        this_.data.array[0].data.first[1].child = [];
      }
      // 重设资产信息
      if (data.data.house == 1) {
        this_.data.array[1].data.first[0].val = '按揭房'
        this_.data.array[1].data.first[0].child = [{
            child_name: '房屋现值',
            child_val: data.data.house_value,
            unit: '万'
          },
          {
            child_name: '月供金额',
            child_val: data.data.monthly_supply,
            unit: '元'
          },
          {
            child_name: '已还期数',
            child_val: data.data.already_repaid,
            unit: '期'
          }
        ];
      } else if (data.data.house == 2) {
        this_.data.array[1].data.first[0].val = '全款房';
        this_.data.array[1].data.first[0].child = [{
          child_name: '房屋现值',
          child_val: data.data.house_value,
          unit: '万'
        }];
      } else {
        this_.data.array[1].data.first[0].val = '无';
        this_.data.array[1].data.first[0].child = [];
      }
      // 车产
      if (data.data.car) {
        this_.data.array[1].data.first[1].val = '有车产';
        this_.data.array[1].data.first[1].child[0].child_val = data.data.car_value;
        this_.data.array[1].data.first[1].child[1].child_val = (data.data.mortgage_status ? '有抵押' : '无抵押');
      } else {
        this_.data.array[1].data.first[1].val = '无';
        this_.data.array[1].data.first[1].child = [];
      }
      // 信用卡
      if (data.data.credit_card) {
        this_.data.array[1].data.first[2].val = '有信用卡';
        this_.data.array[1].data.first[2].child[0].child_val = data.data.credit_total;
        this_.data.array[1].data.first[2].child[1].child_val = data.data.used_total;
      } else {
        this_.data.array[1].data.first[2].val = '无';
        this_.data.array[1].data.first[2].child = [];
      }
      // 微粒贷      
      if (data.data.particulate_loan) {
        this_.data.array[1].data.first[3].val = '有微粒贷';
        this_.data.array[1].data.first[3].child[0].child_val = data.data.particulate_total;
        this_.data.array[1].data.first[3].child[1].child_val = data.data.particulate_used;
      } else {
        this_.data.array[1].data.first[3].val = '无';
        this_.data.array[1].data.first[3].child = [];
      }
      this_.data.array[1].data.first[4].val = (data.data.insurance_policy ? '有保单' : '无保单');
      this_.setData({
        detail: data.data,
        base_info: this_.data.base_info,
        array: this_.data.array,
        cash: data.data.cut,
        fee_id: data.data.cut_id
      })
      if (data.data.out_status == 1) {
        this_.setData({
          cash: data.data.share,
          fee_id: data.data.share_id
        })
      } else if (data.data.out_status == 0) {
        this_.setData({
          cash: data.data.cut,
          fee_id: data.data.cut_id
        })
      }
    });
  },

  buy: function() {
    var this_ = this;
    var discount = this_.data.cash;
    if (discount >= this_.data.balance) {
      this_.setData({
        enoughBalance: false
      })
    } else {
      this_.setData({
        enoughBalance: true
      })
    }
    this_.setData({
      buyIng: false
    })
    wx.showModal({
      title: '温馨提示',
      content: '该客户所有信息均由金融公司同业人员提供，且仅显示客户大致情况，不包含客户直接信息；平台仅提供甩单交流方式，不对该信息做任何担保或保证，请先确认以上信息后再购买！',
      showCancel: false,
      confirmText: '我知道了',
      success: function(res) {
        if (res.confirm) {
          this_.popViewPay.showPopup();
        }
      }
    })
  },

  // 开始支付
  payActivity: function(e) {
    var this_ = this;
    var pwd = e.detail.pwd;
    if (this_.data.buy_type) {
      var body = '客户共享 - ' + this_.data.detail.real_name
    } else {
      var body = '客户买断 - ' + this_.data.detail.real_name
    }
    wx.showLoading({
      title: '支付中...',
    });
    var params = {
      'body': body,
      'cash': this_.data.cash,
      'client_id': this_.data.detail.id,
      'fee_id': this_.data.fee_id,
      'pay_pass': pwd
    };
    app.util.api('pay/balance_pay', 'POST', params, function(data) {
      wx.hideLoading();
      if (data.success) {
        wx.showToast({
          title: '购买成功',
        });
        setTimeout(function() {
          this_.popViewPay.hidePopup();
          wx.navigateBack({})
        }, 800);
      } else if (data.status == 4005) {
        wx.showModal({
          title: '密码错误',
          content: '支付密码不正确',
          confirmText: '找回密码',
          cancelText: '重新输入',
          success: function(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/user/userinfo/bindPhone/bind_phone?send_type=reset_pay_pass',
              })
            } else {
              setTimeout(function() {
                this_.popViewPay.setData({
                  pwd: ''
                })
              }, 500)
            }
          }
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        });
        this_.setData({
          buyIng: true
        });
        this_.popViewPay.setData({
          pwd: ''
        });
        setTimeout(function() {
          wx.hideLoading();
          this_.popViewPay.hidePopup();
        }, 800);
      }
    });
  },

  refresh: function() {
    this.get_detail(this.data.client_id);
    wx.stopPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var this_ = this;
    if (app.globalData.userSys == 'iOS') {
      this_.setData({
        is_ios:true
      })
    }
    var token = wx.getStorageSync('token');
    if (options.type !== undefined) {
      this_.setData({
        is_share: true
      })
    }
    wx.getSystemInfo({
      success: function(res) {
        this_.setData({
          scrollHeight: res.windowHeight
        })
        this_.setData({
          client_id: options.id
        });
        if (options.type !== undefined && !token) {
          app.util.login(function(data) {
            if (data.success == 1) {
              app.data.userinfo = data.data;
              // 储存信息到本地
              wx.setStorageSync('token', data.other);
              this_.get_detail(options.id);
            }
          })
        } else {
          this_.get_detail(options.id);
        }
      },
    })
  },

/**
 * 获取用户信息
 */
  refresh: function (e) {
    var that = this;
    var params = {
      'type': 'userinfo'
    };
    app.util.api('userinfo/center', 'POST', params, function (data) {
      if (data.success == 1) {
        app.data.userinfo = data.data;
        that.setData({
          userinfo: data.data,
          balance: data.data.balance
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.popViewPay = this.selectComponent("#popview_pay");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.refresh();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '客户分享 - ' + this.data.detail.real_name,
      path: '/pages/client/detail/detail?id=' + this.data.detail.id + '&type=share',
    }
  }
})